<template>
    <view class="TemplateModal" v-if="visible">
        <!-- 弹窗遮罩层，点击关闭弹窗 -->
        <view class="modal-overlay"></view>
        <view class="modal-content">
            <!-- 弹窗头部标题 -->
            <view class="modal-header">
                <view class="title">模板选择</view>
            </view>
            <!-- 使用原生 picker 实现下拉菜单 -->
            <view class="dropdown-menu">
                <picker
                        mode="multiSelector"
                        :range="dropdownOptions"
                        @change="onPickerChange"
                        @columnchange="onColumnChange">
                    <view class="dropdown-item">
                        {{ selectedPrimaryLabel || '请选择' }} - {{ selectedSecondaryLabel || '请选择' }}
                    </view>
                </picker>
            </view>
            <!-- 模板列表，支持滚动 -->
            <scroll-view
                         class="template-list"
                         scroll-y
                         @scroll="onScroll">
                <view
                      v-for="(template, index) in filteredTemplates"
                      :key="index"
                      :class="['template-item', { selected: selectedTemplateIndex === index }]"
                      @click="selectTemplate(index)">
                    <image :src="template" class="template-image" mode="aspectFill" />
                </view>
                <!-- 到底提示 -->
                <view v-if="!templateStore.hasNext" class="end-text">--到底了--</view>
            </scroll-view>
            <!-- 底部按钮 -->
            <view class="modal-footer">
                <button class="cancel-btn" @click="closeModal">取消</button>
                <button class="confirm-btn" @click="onConfirm">确定</button>
            </view>
        </view>
    </view>
</template>

<script>
import { autorun, toJS } from "mobx"; // 监听数据变化
import templateStore from "./templateStore";
import utils from "src/utils";
import designEditorRender from "../../DesignEditor/designEditorRender";
import designerStore from "../../DesignEditor/designerStore";
import cloneDeep from "lodash/cloneDeep";
import goodsUtils from "@/utils/goodsUtils";

export default {
    name: "TemplateModal",
    data() {
        return {
            visible: false, // 是否显示弹窗
            dropdownOptions: [[], []], // 二级下拉菜单选项
            selectedPrimaryLabel: "", // 当前选中的一级菜单 label
            selectedSecondaryLabel: "", // 当前选中的二级菜单 label
            data: [],
            templates: [], // 模板数据
            selectedTemplateIndex: null, // 当前选中的模板索引
        };
    },
    computed: {
        filteredTemplates() {
            // 根据选中的分类返回不同的模板列表
            return this.templates;
        }
    },
    methods: {
        onPickerChange(event) {
            const [primaryIndex, secondaryIndex] = event.detail.value;
            const primaryOption = this.dropdownOptions[0][primaryIndex];
            const secondaryOption = this.dropdownOptions[1][secondaryIndex];

            if (primaryOption && secondaryOption) {
                this.selectedPrimaryLabel = primaryOption;
                this.selectedSecondaryLabel = secondaryOption;
            }

            const cascaderOptions = toJS(templateStore.cascaderOptions);
            const primary = cascaderOptions[primaryIndex];
            const secondary = primary?.children?.[secondaryIndex];
            templateStore.setActiveid([primary.value, secondary.value]);
        },
        onColumnChange(event) {
            const { column, value } = event.detail;
            if (column === 0) {
                const selectedPrimary = this.data[value];
                this.dropdownOptions[1] = selectedPrimary?.children?.map(option => option.text) || [];
                this.selectedSecondaryLabel = this.dropdownOptions[1][0] || "请选择";
            }
        },
        initDropdownOptions() {
            if (this.data.length > 0) {
                this.dropdownOptions = [
                    this.data.map(option => option.text),
                    this.data[0]?.children?.map(option => option.text) || []
                ];
                this.selectedPrimaryLabel = this.dropdownOptions[0][0] || "请选择";
                this.selectedSecondaryLabel = this.dropdownOptions[1][0] || "请选择";
            } else {
                this.dropdownOptions = [[], []];
            }
        },
        closeModal() {
            templateStore.setVisible(false);
        },
        onScroll(event) {
            const { scrollHeight, scrollTop } = event.detail;
            const viewHeight = Taro.getWindowInfo().windowHeight - 300;
            if (scrollHeight - scrollTop - viewHeight < 100) {
                templateStore.getNextPage();
            }
        },
        selectTemplate(index) {
            this.selectedTemplateIndex = index;
        },
        async onConfirm() {
            const selectedTemplate = toJS(templateStore.templates)[this.selectedTemplateIndex];
            if (selectedTemplate) {
                const { goodsData, activeComponent, goodsDataComponents } = designerStore;
                if (goodsData) {
                    const component = goodsDataComponents.find(c => c.key === activeComponent);
                    if (component) {
                        const { print_area_left, print_area_top, print_area_width, print_area_height } = component;
                        let offsetLeft = 0; // 根据打印位置计算模版元素的偏移量
                        let offsetTop = 0;
                        let offsetScale = 1;
                        const { modalSize } = goodsData;
                        const size = await goodsUtils.computerComponentSize(component, modalSize); // 计算组件尺寸

                        const sideLength = Math.max(size.width, size.height) * (1 / 2.8346); // 取宽和高中较大的值作为边长
                        // 200mm*265mm 的局部印 和 280mm*350mm的局部印
                        if ([200, 280].includes(print_area_width)) {
                            offsetScale = (print_area_width / sideLength) / (400 / 1024);
                            offsetLeft = ((print_area_left + (print_area_width / 2)) / sideLength) * 1024 - 200;
                            offsetTop = ((print_area_top + (print_area_height / 2)) / sideLength) * 1024 - 265;
                            //满版印就居中
                        } else {
                            offsetScale = 1;
                            offsetLeft = (512 - 200);
                            offsetTop = (512 - 265);
                        }

                        const designData = cloneDeep(selectedTemplate.designData);

                        designData.objects.map((o) => {
                            o.left += offsetLeft;
                            o.top += offsetTop;
                            o.scaleX *= offsetScale;
                            o.scaleY *= offsetScale;
                        });
                        // 保留底色
                        designData.background = designEditorRender.background;
                        designEditorRender.loadFromJSON(designData, () => {

                        });
                    }
                }
                templateStore.setVisible(false);
            }
        }
    },
    mounted() {
        this.dispose = autorun(() => {
            this.data = toJS(templateStore.cascaderOptions);
            this.initDropdownOptions();
        });
        this.dispose2 = autorun(() => {
            const templates = toJS(templateStore.templates); // 监听图片列表变化
            this.templates = templates.map(item => utils.ossSuffix(item.thumb, 512));
        });
        this.dispose3 = autorun(() => {
            this.visible = templateStore.visible;
        });
    },
    destroyed() {
        this.dispose();
        this.dispose2();
        this.dispose3();
    }
};
</script>

<style scoped lang="scss">
.TemplateModal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;

    .modal-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
    }

    .modal-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        background: #ffffff;
        border-radius: 8px;
        overflow: hidden;
        display: flex;
        flex-direction: column;

        .modal-header {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 12px;
            background: #f5f5f5;
            border-bottom: 1px solid #e6e6e6;

            .title {
                font-size: 16px;
                font-weight: bold;
                color: #333333;
            }
        }

        .dropdown-menu {
            padding: 8px 12px;
            background: #f9f9f9;
            border-bottom: 1px solid #e6e6e6;

            .dropdown-item {
                text-align: center;
                padding: 8px;
                background: #ffffff;
                border: 1px solid #cccccc;
                border-radius: 4px;
                font-size: 14px;
                color: #333333;
            }
        }

        .template-list {
            padding: 12px;
            width: 100%;
            box-sizing: border-box;
            height: calc(100vh - 300px);
            overflow-y: auto;
            display: block;

            .template-item {
                display: inline-block;
                width: 50%;
                height: 120px;
                border-radius: 4px;
                border: 2px solid transparent;
                box-sizing: border-box;

                &.selected {
                    border-color: #FF5E10;
                }

                .template-image {
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                }
            }

            .end-text {
                width: 100%;
                text-align: center;
                font-size: 14px;
                color: #999999;
                margin-top: 10px;
            }
        }

        .modal-footer {
            display: flex;
            justify-content: space-between;
            padding: 12px;
            background: #f5f5f5;
            border-top: 1px solid #e6e6e6;

            .cancel-btn {
                flex: 1;
                margin-right: 8px;
                padding: 2px 8px;
                background: #ffffff;
                border: 1px solid #cccccc;
                border-radius: 4px;
                font-size: 14px;
                color: #333333;
                text-align: center;
            }

            .confirm-btn {
                flex: 1;
                margin-left: 8px;
                padding: 2px 8px;
                background: #FF5E10;
                border: none;
                border-radius: 4px;
                font-size: 14px;
                color: #ffffff;
                text-align: center;
            }
        }
    }
}
</style>
